import Request from "@/plugin/luch-request/index.js";
import env from "@/config/index.js";
import store from "@/store/index.js";
import {
	toBack,
	toLogin,
	getRoutePath
} from "@/common/js/page-handle.js";
import {
	toast
} from "@/common/js/utils.js";

let isSkip = false;
const http = new Request();
/**
 * @description 修改全局默认配置 https://www.quanzhan.co/luch-request/guide/3.x/#%E5%8F%AF%E9%85%8D%E7%BD%AE%E9%A1%B9
 * @param {Function}   
 */

http.setConfig((config) => {
	/* config 为默认全局配置*/
	config.baseURL = env.baseUrl + '/api'
	// 全局的请求头
	config.header = {
		server: 1
	}
	// 自定义params 处理函数
	// config.paramsSerializer = (v) => {

	// }
	// 超时时间
	config.timeout = 10000

	// 全局自定义验证器。参数为statusCode 且必存在，不用判断空情况。
	validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置
		return statusCode >= 200 && statusCode < 300
	}
	return config
})

// 请求拦截
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	config.header = {
		...config.header,
	}
	let token = store.state.vuex_token
	if (token) {
		config.header['ba-user-token'] = token
	}
	// 自动添加请求头
	return config
}, config => { // 可使用async await 做异步操作
	return Promise.reject(config)
})

// 响应拦截
http.interceptors.response.use((response) => {
	/* 对响应成功做点什么 可使用async await 做异步操作*/
	// console.log(response, "响应成功");
	if (response.data.code != 1) {
		handleError(response);
		return Promise.reject(response);
	}
	return response.data
}, (response) => {
	/*  对响应错误做点什么 （statusCode !== 200）*/
	handleError(response);
	return Promise.reject(response);
});


const handleError = (res) => {
	if (res.errMsg == "request:fail timeout") {
		// let config = res.config;
		// let method = config.method.toLocaleLowerCase();
		// return http[method](config.fullPath,config.data);
		toast("网络不稳定，请重试");
		return;
	}

	let data = res.data;
	// console.log("错误状态", res, data);
	let status = data.hasOwnProperty('code') ? data.code : res.statusCode;
	switch (status) {
		case 0: {
			return toast(data.msg);
		};
		case 409:
		case 302: {
			isSkip = true
			return toast(data.msg, () => {
				if (isSkip) {
					isSkip = false;
					store.dispatch('exitLogin');
					let route = getRoutePath(true);
					store.commit("$uStore", {
						name: "vuex_back_link",
						value: route
					});
					toLogin(1);
				}
			});
		};
		case 500: {
			return toast("系统发生错误,请稍后重试", toBack);
		}
	}
}


export default http